package cn.net.cfss.fgbp.face.console.filter;

import cn.net.cfss.fgbp.base.common.GlobalConstants;
import cn.net.cfss.fgbp.base.constant.ErrCodeEnum;
import cn.net.cfss.fgbp.face.console.util.ReturnUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author oygq
 * @title: LoginFilter
 * @description: 登录过滤器，判断用户是否登录
 * @date 2019/5/7 10:45
 */

@Slf4j
@WebFilter(filterName = "loginFilter",urlPatterns = {"/*"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("loginFilter init");
    }

    /**
     * 请求头未包含用户信息，直接返回错误信息
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
         if(request instanceof HttpServletRequest){
            HttpServletRequest req = (HttpServletRequest) ((HttpServletRequest) request);
            String userId = req.getHeader(GlobalConstants.HEADER_USERID);
            if(StringUtils.isBlank(userId)){
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(ReturnUtil.returnErr(ErrCodeEnum.INVALID_TOKEN));
            }else {
                chain.doFilter(request, response);
            }
        }
    }

    @Override
    public void destroy() {
        log.info("loginFilter destroy");
    }
}
